﻿using System.Net;
using UnityEngine;

namespace xinhyue.game.client.frame.stream
{

    public class CodecFactory
    {

        public static byte[] EncodeMessage(IGameMessage request)
        {
            GameMessageHeader header = request.GetHeader();
            int totalSize = GameMessageHeader.HEADER_WRITE_LENGTH + 4;

            byte[] bodyBytes = request.Write();
            if (bodyBytes != null)
            {
                Debug.Log("向网关发送包体长度：" + bodyBytes.Length);
                totalSize += bodyBytes.Length;
                               //TODO 添加包体是否压缩的判断
                if (bodyBytes.Length > GameClientConfig.CompressSize)
                {
                    header.IsCompress = true;
                    //TODO 对消息进行压缩
                }
                //TODO 对消息进行加密

            }

            ByteBuf byteBuf = new ByteBuf(totalSize);
            byteBuf.WriteInt(totalSize);
            header.Write(byteBuf);
            if (bodyBytes != null)
            {
                
                byteBuf.WriteBytes(bodyBytes);
               
            }
            return byteBuf.ToArray();
        }

        public static void DecodeMessage(ByteBuf byteBuf, IGameMessage gameMessage)
        {
            GameMessageHeader header = gameMessage.GetHeader();
            header.Read(byteBuf);
            if (byteBuf.IsReadable())
            {
                int size = byteBuf.ReadableBytes();
                byte[] bytes = new byte[size];
                byteBuf.ReadBytes(bytes);
                if (header.IsCompress)
                {
                    //TODO 服务器对数据进行了压缩，这里要进行一下解压缩

                }
                if (header.IsEncrypt)
                {
                    //TODO 对消息进行解密
                }
                gameMessage.Read(bytes);
                Debug.Log("接收消息:" + gameMessage.GetHeader().MessageSeqId + "，" + gameMessage.GetHeader().MessageId);
            }

        }
    }
}
